import matplotlib
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['SimHei']
pyplot.rcParams['axes.unicode_minus'] = False
import matplotlib.pyplot as plt 

class MyFigure(FigureCanvasQTAgg):
    def __init__(self, width=5, height=4, dpi=100):
        """初始化图表，固定y轴范围为-8000到8000"""
        self.fig = plt.Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        super().__init__(self.fig)
        
        # 固定设置y轴范围为-8000到8000
        self.y_min = -10000
        self.y_max = 10000
        self.axes.set_ylim(self.y_min, self.y_max)
        
        self.axes.set_title('力传感器数据实时显示')
        self.axes.set_xlabel('采样点')
        self.axes.set_ylabel('力值')
        self.axes.grid(True)
        self.batch_number = 0
        self.max_points = 100  # 固定x轴显示的最大点数
        
    def plotFig(self, x, y_x, y_y, y_z):
        self.axes.clear()
        
        # 确保x轴数据不超过max_points
        x = x[-self.max_points:]
        y_x = y_x[-self.max_points:]
        y_y = y_y[-self.max_points:]
        y_z = y_z[-self.max_points:]
        
        self.axes.plot(x, y_x, 'r-', label='Force X')
        self.axes.plot(x, y_y, 'g-', label='Force Y')
        self.axes.plot(x, y_z, 'b-', label='Force Z')
        
        self.axes.set_ylim(self.y_min, self.y_max)
        self.axes.set_title(f'力传感器数据实时显示 - 批次 {self.batch_number}')
        self.axes.set_xlabel('采样点')
        self.axes.set_ylabel(f'力值 (范围: {self.y_min} ~ {self.y_max})')
        self.axes.grid(True)
        self.axes.legend()
        
        # 设置x轴显示范围（始终显示0到max_points-1）
        self.axes.set_xlim(0, self.max_points - 1)
        self.fig.tight_layout()
        self.draw()
        
    def clear_chart(self, batch_number=None):
        self.axes.clear()
        self.axes.set_ylim(self.y_min, self.y_max)
        self.axes.set_xlim(0, self.max_points - 1)  # 设置x轴范围
        self.axes.set_title('力传感器数据实时显示')
        self.axes.set_xlabel('采样点')
        self.axes.set_ylabel(f'力值 (范围: {self.y_min} ~ {self.y_max})')
        self.axes.grid(True)
        if batch_number is not None:
            self.batch_number = batch_number
        self.draw()
        
    def set_fixed_ylim(self, y_min=-8000, y_max=8000):
        """设置y轴范围为-8000到8000（也可传入其他值覆盖）"""
        self.y_min = y_min
        self.y_max = y_max
        self.axes.set_ylim(self.y_min, self.y_max)
        self.axes.set_ylabel(f'力值 (范围: {self.y_min} ~ {self.y_max})')
        self.draw()